#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cre2.h>

#define PRINTF(...) { printf(__VA_ARGS__);         fflush(stdout); }
#define FWRITE(...) { fwrite(__VA_ARGS__, stdout); fflush(stdout); }

int main (void)
{
    { /* 引用元字符 */
        const char *pattern = "1.5-2.0?";
        cre2_string_t original = {.data = pattern, .length = strlen(pattern)};
        cre2_string_t quoted;
        int result;

        result = cre2_quote_meta(&quoted, &original);

        if (0 != result)
            goto error;
        if (0 != strncmp("1\\.5\\-2\\.0\\?", quoted.data, quoted.length))
            goto error;

        free((void *)quoted.data);
    }

    { /* 最短和最长匹配 */
        const char *pattern = "(?i)ABCdef";
        cre2_regexp_t *rex;
        cre2_string_t min, max;
        int result;

        rex = cre2_new(pattern, strlen(pattern), NULL);

        {
            result = cre2_possible_match_range(rex, &min, &max, 1024);

            if (1 != result)
                goto error;
            if (0 != strncmp("ABCDEF", min.data, min.length))
                goto error;
            if (0 != strncmp("abcdef", max.data, max.length))
                goto error;
        }

        cre2_delete(rex);
        free((void *)min.data);
        free((void *)max.data);
    }

    { /* 替换字符串检查(成功) */
        const char *pattern = "a(b)c";
        const char *subst   = "def";
        cre2_string_t rewrite = {.data = subst, .length = strlen(subst)};
        cre2_regexp_t *rex;
        cre2_string_t errmsg;
        int result;

        rex = cre2_new(pattern, strlen(pattern), NULL);

        {
            result = cre2_check_rewrite_string(rex, &rewrite, &errmsg);

            if (1 != result)
                goto error;
        }

        cre2_delete(rex);
    }
    { /* 替换字符串检查(失败) */
        const char *pattern = "a(b)c";
        const char *subst = "\\1 \\2";
        cre2_string_t rewrite = {.data = subst, .length = strlen(subst)};
        cre2_regexp_t *rex;
        cre2_string_t errmsg;
        int result;

        rex = cre2_new(pattern, strlen(pattern), NULL);

        {
            result = cre2_check_rewrite_string(rex, &rewrite, &errmsg);

            if (0 != result)
                goto error;

            PRINTF("error message: ");
            FWRITE(errmsg.data, errmsg.length, 1);
            PRINTF("\n");
        }

        cre2_delete(rex);
        free((void *)errmsg.data);
    }

    exit(EXIT_SUCCESS);
error:
    exit(EXIT_FAILURE);
}
